package com.jd.after.modules.sys.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jd.after.common.core.P;
import com.jd.after.modules.mis.dao.BlogDao;
import com.jd.after.modules.mis.entity.Blog;
import com.jd.after.modules.sys.dao.UserDao;
import com.jd.after.modules.sys.entity.User;
import com.jd.after.modules.sys.entity.UserRole;
import com.jd.after.modules.sys.service.UserRoleService;
import com.jd.after.modules.sys.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
   
    @Autowired
    UserDao userDao;

    @Autowired
    BlogDao blogDao;

    @Autowired
    UserRoleService  userRoleService;

    // /**
    //  * MP分页，分页插件MybatisPlusInterceptor
    //  * 
    //  * dao层方法的第一个参数需要是IPage
    //  * 
    //  * 分页参数传递
    //  * P.page(params)  return new Page<>(curPage, limit);
    //  * 
    //  * params=》(传递条件)
    //  * 
    //  */
    // @Override
    // public IPage<Map<String, Object>> q1(Map<String, Object> params) {

    //     IPage<Map<String, Object>> result= userDao.daoQ1(P.page(params),params);       

    //     return result;
    // }
    
    /**
     * 删除用户和用户的博客
     * 当有多个增删改dao方法在一个service方法里时，为保证数据一致性，要加上事务注解
     * @Transactional(rollbackFor = Exception.class)
     * 
     * 遇到异常会回滚
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUserAndBlog(Long id) {


        int r1=userDao.deleteById(id);   //DELETE FROM m_user WHERE id=?

        int i=1/0;   //模拟异常

        QueryWrapper<Blog> qw = new QueryWrapper<>();
        qw.eq("user_id", id);
        int r2=blogDao.delete(qw);      //DELETE FROM m_blog WHERE (user_id = ?)
        
        return true;
    }


     /**
       * 保存用户和角色 

      */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserAndRole(User entity) {
        //保存用户
        entity.setCreateTime(LocalDateTime.now());
        this.save(entity);    //回传会 id 
        System.out.println(entity);
       
        //保存角色
        List<UserRole> list=new ArrayList<UserRole>();
        for(Long rid : entity.getYesCheckList()){
            UserRole ur=new UserRole();
            ur.setUserId(entity.getId());
            ur.setRoleId(rid);
            list.add(ur);
        }

        System.out.println(list);
         
        userRoleService.saveBatch(list);   //批量保存角色
        
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserAndRole(User entity) {
        //1.更新用户表  UPDATE sys_user SET name=?, password=?, birthday=?, email=?, avatar=?, create_time=? WHERE id=?
        this.updateById(entity);

        //2.删除所有旧关系  DELETE FROM sys_user_role WHERE (user_id = ?)
       userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id", entity.getId()));
      
      
       //3.添加新关系   INSERT INTO sys_user_role ( user_id, role_id ) VALUES ( ?, ? )
         //保存角色
         List<UserRole> list=new ArrayList<UserRole>();
         for(Long rid : entity.getYesCheckList()){
             UserRole ur=new UserRole();
             ur.setUserId(entity.getId());
             ur.setRoleId(rid);
             list.add(ur);
         }

         userRoleService.saveBatch(list);   //批量保存角色
              
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserAndRole(Long[] ids) {
        //1.删除自身 DELETE FROM sys_user WHERE id IN ( ? )
        this.removeByIds(Arrays.asList(ids));

        //2.删除关系  DELETE FROM sys_user_role WHERE (user_id = ?)
        for(Long id : ids){
            userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id", id));
        }
        
    }

   
    

}
